package com.mrlv.rabbitmq;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description: 生产一个吃一个，生产者与消费者
 * @author Mrlv
 * @date 2021年11月17日 16:15
 * @version 1.0
 */
public class ThreadWaitNotifyDemo {
    public static void main(String[] args) {
        Basket basket = new Basket();

        new Thread(() ->{
            for (int i = 0; i < 10; i++) { basket.input(); }
        }, "生产者1").start();

        new Thread(() ->{
            for (int i = 0; i < 10; i++) { basket.input(); }
        }, "生产者2").start();


        new Thread(() ->{
            for (int i = 0; i < 10; i++) { basket.output(); }
        }, "消费者1").start();

        new Thread(() ->{
            for (int i = 0; i < 10; i++) { basket.output(); }
        }, "消费者2").start();
    }

}


class Basket {

    private int number = 0;

    private Lock lock = new ReentrantLock();

    private Condition condition = lock.newCondition();

    public void input() {
        lock.lock();
        try {
            while (number != 0) { condition.await(); }
            System.out.println(Thread.currentThread().getName() + ": 生产一个产品，当前产品总数为" + (++number));
            condition.signalAll();
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }


    public void output(){
        lock.lock();
        try {
            while (number == 0) { condition.await(); }
            System.out.println(Thread.currentThread().getName() + ": 消费一个产品，当前产品总数为" + (--number));
            condition.signalAll();
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}